var Crops = require("Crops");
var CropsStage = require("CropsStage");
var User = require("User");
var UserCrops = require("UserCrops");

var Controller = cc.Class({
    extends: cc.Component,

    properties: {
        cropsPerfab : cc.Prefab,
        shopPerfab : cc.Prefab,
        userPerfab : cc.Prefab,

        fatherNode : cc.Node,
        ui_new : cc.Node,
        ui_choose : cc.Node,
        ui_shop : cc.Node,
        ui_back : cc.Node,
        ui_shop_content : cc.Node,
        ui_user_coin : cc.Label,
        ui_user_name : cc.Label,
        ui_user_list : cc.Node,

        choose_crops : cc.Node,
        choose_buy : 0,

        m_user : User,
        m_crops : Crops,
        m_client : null,
        m_name : "Finch",

        cropsList : [cc.Node],
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    createCrops(fatherNode,userCrops){
        var crops = cc.instantiate(this.cropsPerfab);
        //var userCrops = new UserCrops();
        //userCrops.CropsIndex = CropsIndex;
        //userCrops.time = time;
        crops.getComponent("CropsTemplate").controller = this;
        crops.getComponent("CropsTemplate").userCrops = userCrops;
        crops.getComponent("CropsTemplate").init();
        fatherNode.addChild(crops);
        this.cropsList.push(crops);
    },

    createShopContent(fatherNode,cropsIndex){
        var content = cc.instantiate(this.shopPerfab);
        content.getComponent("sellTemplate").controller = this;
        content.getComponent("sellTemplate").cropsIndex = cropsIndex;
        content.getComponent("sellTemplate").init();
        fatherNode.addChild(content);
    },

    updateUserInform(){
        this.ui_user_name.string = "[User]" + this.m_name;
        this.ui_user_coin.string ="[coin]" + this.m_user.coin;
    },

    calcStage(userCrops,CropsList){
        var ins_crop = CropsList[userCrops.CropsIndex];
        var sum = 0,i=0,deltaTime =(Date.parse(new Date()) - userCrops.time)/1000;
        //console.log(deltaTime);
        while(i<ins_crop.stages.length){
            sum += ins_crop.stages[i].time;
            if(deltaTime >= sum){
                ++i;
            }else {
                break;
            }
        }
        if(i==ins_crop.stages.length)i=ins_crop.stages.length-1;
        return [ins_crop.stages[i],i];
    },
/*
    save(){
        cc.sys.localStorage.setItem('User',JSON.stringify(this.m_user));
    },
*/
    RevRes(){
        this.m_crops = JSON.parse(require("../resources/cropsData"));
        this.ui_shop.active = true;
        for (var i = 0;i<this.m_crops.length;++i){
            this.createShopContent(this.ui_shop_content,i);
        }
        this.ui_shop.active = false;
    },

    RevUser(data){
        /*
        this.m_user = JSON.parse(cc.sys.localStorage.getItem('User'));
        this.m_crops = JSON.parse(require("../resources/cropsData"));
        if(this.m_user == null){
            this.m_user = new User();
        }
        */
       
       this.m_user = JSON.parse(data);
       if(this.m_user == null){
            this.m_user = new User();
       }

       this.updateUserInform();
       
       this.cropsList.length = 0;
       this.fatherNode.removeAllChildren();
       for (var i = 0;i<this.m_user.crops.length;++i){
           this.createCrops(this.fatherNode,this.m_user.crops[i]);
       }
    },

    RevList(data){
        //data is a list of user name string
        //we can use it to get other users' data and modify them
        var list = JSON.parse(data);
        for(var i = 0; i < list.length;++i){
            var content = cc.instantiate(this.userPerfab);
            content.getComponent("userNameTemplate").m_name = list[i];
            content.getComponent("userNameTemplate").m_controller = this;
            this.ui_user_list.addChild(content);
        }
    },

    upload(){
        this.m_client.sendMsg(2,{name : this.m_name, data : JSON.stringify(this.m_user)});
    },

    download(){
        this.m_client.sendMsg(3,{name : this.m_name});
    },

    getList(){
        this.m_client.sendMsg(1,null);
    },

    start () {
        this.RevRes();

        this.m_client = require("client");
        this.m_client.RevUser = this.RevUser.bind(this);
        this.m_client.RevList = this.RevList.bind(this);

        this.download();//send download user data requests
        this.getList();

        //regist some events such like update crops' statges and click event
        
        this.ui_back.on(cc.Node.EventType.TOUCH_END,function(t){
            this.ui_new.active = true;
            this.ui_new.setPosition(t.touch.getLocation());
        },this);

        this.schedule(function(){
            for (var i = 0;i<this.cropsList.length;++i){
                var m_stage = this.calcStage(this.cropsList[i].getComponent("CropsTemplate").userCrops,this.m_crops);
                if(this.cropsList[i].getComponent("CropsTemplate").cur_stage != m_stage[1]){
                    var tmp = this.cropsList[i].getComponent("CropsTemplate");
                    cc.loader.loadRes(m_stage[0].picture,function(err,spriteFrame){
                        tmp.pic.spriteFrame = new cc.SpriteFrame(spriteFrame);
                        //[ENGINE BUG]here the engine can't call node.getComponet() --- may because of asyn
                    }.bind(this));
                    this.cropsList[i].getComponent("CropsTemplate").cur_stage = m_stage[1];
                }
                var m_stage_full = this.m_crops[this.cropsList[i].getComponent("CropsTemplate").userCrops.CropsIndex].stages.length;
                this.cropsList[i].getComponent("CropsTemplate").ui_time.string = m_stage[1]+1+"/"+m_stage_full;
            }
        }.bind(this),1);
    },

    get(){
        var m_stage = this.calcStage(this.choose_crops.getComponent("CropsTemplate").userCrops,this.m_crops)[0];
        this.m_user.coin +=m_stage.sell;
        this.updateUserInform();
        for(var i = 0 ;i<this.m_user.crops.length;++i){
            if(this.choose_crops.getComponent("CropsTemplate").userCrops === this.m_user.crops[i]){
                this.m_user.crops.splice(i,1);
                break;
            }
        }
        for (var i = 0;i<this.cropsList.length;++i){
            if(this.choose_crops === this.cropsList[i]){
                this.cropsList.splice(i,1);
                break;
            }
        }
        this.choose_crops.destroy();
        this.ui_choose.active = false;
    },

    openShop(){
        this.ui_shop.active = true;
        this.ui_new.active = false;
    },
    closeShop(){
        this.ui_shop.active = false;
    },
    buy(){
        var ins_crops = this.m_crops[this.choose_buy];
        this.m_user.coin -= ins_crops.cost;
        this.updateUserInform();
        var user_crops = new UserCrops();
        user_crops.time = Date.parse(new Date());
        user_crops.CropsIndex = this.choose_buy;
        this.m_user.crops.push(user_crops);
        this.createCrops(this.fatherNode,user_crops);
    },

    onDestroy(){
        this.upload();

    },

    // update (dt) {},
});
